import time
import streamlit as st
import streamlit_antd_components as sac
from streamlit.components.v1 import html
from authentication import load_config, init_authenticator, login_page, is_default_password, check_password_expiry, update_password_change_date
from admin import admin_page
from user import user_page
from data_utils import load_data
from models import init_db, Session, Calculator, Task

LOGO_BIG = "https://r2.keldos.me/your-logo-big.png"
LOGO_SMALL = "https://r2.keldos.me/your-logo-small.svg"
LOGO_DESCRIPTION = "Your description here."

# 初始化数据库表结构
init_db()

# 初始化session_state
if 'authenticated' not in st.session_state:
    st.session_state.authenticated = False

if 'username' not in st.session_state:
    st.session_state.username = None

if 'roles' not in st.session_state:
    st.session_state.roles = []

def main():
    # 读取并注入自定义样式和脚本
    with open('static/styles.css', encoding='utf-8') as f:
        css = f.read()
    with open('static/script.js', encoding='utf-8') as f:
        js = f.read()
    st.markdown(f'<style>{css}</style>', unsafe_allow_html=True)

    authenticator = init_authenticator()

    # 登录页面
    # 仅在未登录时显示登录页面的 logo
    if not st.session_state.get("authentication_status"):
        with st.container(key="login_container"):
            st.image(LOGO_SMALL, width=80)  # 添加logo图片
            st.subheader(LOGO_DESCRIPTION)  # 添加logo描述

    login_page(authenticator)

    # 若已登录成功
    if st.session_state["authentication_status"]:
        user_data = load_config()["credentials"]["usernames"].get(st.session_state.username, {})

        # 检查用户状态
        if user_data.get("status", "Active") == "Suspended":
            st.error("您的账号已被停用，请联系管理员。")
            authenticator.logout("登出")
            return

        # 检查是否需要重置密码
        password_requirement = "密码要求：\n1. 长度为 8 到 20 个字符\n2. 必须包含大小写字母、数字和特殊字符。\n3. 特殊字符：@$!%*?&"
        if is_default_password(st.session_state.username, user_data.get("password", "")):
            st.warning("请修改您的初始密码")
            st.info(password_requirement)
            authenticator.logout("登出")
            try:
                if authenticator.reset_password(st.session_state.username, key='Reset Password'):
                    st.success('密码修改成功！请重新登录。')
                    time.sleep(2)
                    update_password_change_date(st.session_state.username)
                    st.rerun()
            except Exception as e:
                st.error(e)
            return

        if check_password_expiry(st.session_state.username):
                st.warning("您的密码已过期，请修改密码")
                st.info(password_requirement)
                authenticator.logout("登出")
                if authenticator.reset_password(st.session_state.username):
                    st.success('密码已更新')
                    time.sleep(2)
                    update_password_change_date(st.session_state.username)
                    st.rerun()
                return

        # 检查用户状态
        if user_data.get("status", "Active") == "Suspended":
            st.error("您的账号已被停用，请联系管理员。")
            authenticator.logout("登出")
            return

        with st.sidebar:
            # 之后更改为自己的 logo
            st.logo(LOGO_BIG)

            col1, col2, col3, col4 = st.columns(4, vertical_alignment="center")
            # 用户头像
            with col1:
                # st.write(icon="person-circle", width=50, height=50)
                st.markdown("""<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="currentColor" class="bi bi-person-circle" viewBox="0 0 16 16"><path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0"/><path fill-rule="evenodd" d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8m8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1"/></svg>""", unsafe_allow_html=True)

            with col2:
                st.title(f"{st.session_state.username}")

            with col3:
                if any(role in st.session_state.roles for role in ["sysadmin", "calcadmin", "statusadmin"]):
                    sac.tags([sac.Tag(label='Admin')])
                else:
                    sac.tags([sac.Tag(label='User')])

            with col4:
                authenticator.logout("", key="sidebar_logout")

        # 路由逻辑：看角色给不同页面入口
        if st.session_state.roles is not None:
            if any(role in st.session_state.roles for role in ["sysadmin", "calcadmin", "statusadmin"]):
                page = st.sidebar.selectbox("请选择页面", ["管理页面", "用户页面"], key="page_selector")
                if page == "管理页面":
                    admin_page()
                else:
                    user_page()
            else:
                # 普通用户直接进用户页面
                user_page()

    elif st.session_state["authentication_status"] is False:
        st.error("用户名或密码错误，请重试。")
    elif st.session_state["authentication_status"] is None:
        st.warning("请输入用户名和密码进行登录。")

    # with st.container(key = "script_container", height=0):
    #     html(f"<script>{js}</script>", height=0)

if __name__ == "__main__":
    main()
